//定义电影演员相关接口
const express = require("express");
const router = express.Router();
//引入mysql连接池
const pool = require("../utils/db");
//引入joi表单验证模块
const Joi = require("joi");
//引入响应对象模块
const Response = require("../utils/Response");
//通过电影关键字模糊查询电影
///movie-infos/name
router.post("/movie-infos/name", async (req, resp) => {
  //获取请求参数 get请求的参数分装在req.query中

  let { name, page, pagesize } = req.body;
  //需要对服务端传入的值进行验证（服务端表单验证）(joi模块)
  //查询数据库
  let schema = Joi.object({
    page: Joi.number().required(), //page必须是数字，必填
    name: Joi.string().required(),
    pagesize: Joi.number().integer().max(100).required(), //pagesize必须是不大于100的数字，必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  //执行查询业务
  try {
    let startIndex = (page - 1) * pagesize;
    let size = parseInt(pagesize);
    let sql = "select * from movie_info where title like ? limit ?,?";
    let result = await pool.querySync(sql, [`%${name}%`, startIndex, size]);
    //执行查询总条目数
    let sql2 = "select count(*) as count from movie_info where title like ? ";
    let result2 = await pool.querySync(sql2, [`%${name}%`]);
    let total = result2[0].count;
    resp.send(
      Response.ok({ page: parseInt(page), pagesize: size, total, result })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});
//为电影绑定演员列表接口
///movie-info/bind-actors
router.post("/movie-info/bind-actors", async (req, resp) => {
  let { movie_id, actor_ids } = req.body;
  //表单验证
  let schema = Joi.object({
    movie_id: Joi.string().required(),
    actor_ids: Joi.allow(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  try {
    //执行sql,将当前movie_id数据全部删除
    let sql1 = "delete from movie_info_map_actor where movie_id = ?";
    await pool.querySync(sql1, [movie_id]);
    if (!actor_ids) {
      resp.send(Response.ok());
      return;
    }
    //执行sql,将movie_id和 actor_ids绑定
    let params = "";
    let paramsArray = [];
    let ids = actor_ids.split(",");
    for (let i = 0; i < ids.length; i++) {
      params += "(?,?),";
      paramsArray.push(movie_id);
      paramsArray.push(ids[i]);
    }
    let sql2 =
      "insert into movie_info_map_actor (movie_id,actor_id) values" + params;
    sql2 = sql2.substring(0, sql2.length - 1);
    await pool.querySync(sql2, paramsArray);
    resp.send(Response.ok());
  } catch (error) {
    resp.send(Response.error(500, error));
  }
});
//更新电影信息接口
//接口地址/movie-info/update
router.post("/movie-info/update", (req, resp) => {
  let {
    id,
    category_id,
    cover,
    title,
    type,
    star_actor,
    showingon,
    score,
    description,
    duration,
  } = req.body;
  //表单验证
  let schema = Joi.object({
    id: Joi.number().required(),
    category_id: Joi.number().required(),
    cover: Joi.string().required(),
    title: Joi.string().required(),
    type: Joi.string().required(),
    star_actor: Joi.string().required(),
    showingon: Joi.string().required(),
    score: Joi.string().required(),
    description: Joi.string().required(),
    duration: Joi.number().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  //表单验证通过，执行更新电影操作
  let sql = `update movie_info set category_id =?,cover=?,title=?,type=?,star_actor=?,showingon=?,score=?,description=?,duration=? where id = ?`;
  pool.query(
    sql,
    [
      category_id,
      cover,
      title,
      type,
      star_actor,
      showingon,
      score,
      description,
      duration,
      id,
    ],
    (error, result) => {
      if (error) {
        resp.send(Response.error(500, error));
        throw err;
      }
      resp.send(Response.ok());
    }
  );
});
//删除电影接口
//接口地址/movie-info/del
router.post("/movie-info/del", (req, resp) => {
  let { id } = req.body;
  //表单验证
  let schema = Joi.object({
    id: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  //执行删除业务
  let sql = "delete from movie_info where id = ?";
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});
//根据id查找电影
//接口地址/movie-info/name
router.get("/movie-info/sel", (req, resp) => {
  let { id } = req.query;
  //表单验证
  let schema = Joi.object({
    id: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  let sql = "select * from movie_info where id= ?";

  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw err;
    }
    if (result && result.length == 0) {
      resp.send(Response.ok(null));
    } else {
      resp.send(Response.ok(result[0]));
    }
  });
});
//查询所有电影
///movie-infos
router.get("/movie-infos", async (req, resp) => {
  //获取请求参数 get请求的参数分装在req.query中

  let { page, pagesize } = req.query;
  //需要对服务端传入的值进行验证（服务端表单验证）(joi模块)
  //查询数据库
  let schema = Joi.object({
    page: Joi.number().required(), //page必须是数字，必填
    pagesize: Joi.number().integer().max(100).required(), //pagesize必须是不大于100的数字，必填
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  try {
    let startIndex = (page - 1) * pagesize;
    let size = parseInt(pagesize);
    let sql = "select * from movie_info limit ?,?";
    let result = await pool.querySync(sql, [startIndex, size]);
    //执行查询总条目数
    let sql2 = "select count(*) as count from movie_info";
    let result2 = await pool.querySync(sql2, [startIndex, size]);
    let total = result2[0].count;
    resp.send(
      Response.ok({ page: parseInt(page), pagesize: size, total, result })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});
//查询电影类型接口
///movie-types
router.get("/movie-types", (req, resp) => {
  let sql = "select * from movie_type";
  pool.query(sql, (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw err;
    }
    resp.send(Response.ok(result));
  });
});
//添加电影接口
//接口地址/movie-info/add
router.post("/movie-info/add", (req, resp) => {
  let {
    categoryId,
    cover,
    title,
    type,
    starActor,
    showingon,
    score,
    description,
    duration,
  } = req.body;
  //表单验证
  let schema = Joi.object({
    categoryId: Joi.number().required(),
    cover: Joi.string().required(),
    title: Joi.string().required(),
    type: Joi.string().required(),
    starActor: Joi.string().required(),
    showingon: Joi.string().required(),
    score: Joi.string().required(),
    description: Joi.string().required(),
    duration: Joi.number().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  //表单验证通过，执行添加操作
  let sql = `insert into movie_info 
  (category_id,cover,title,type,star_actor,showingon,score,description,duration) 
    values (?,?,?,?,?,?,?,?,?)`;
  pool.query(
    sql,
    [
      categoryId,
      cover,
      title,
      type,
      starActor,
      showingon,
      score,
      description,
      duration,
    ],
    (error, result) => {
      if (error) {
        resp.send(Response.error(500, error));
        throw err;
      }
      resp.send(Response.ok());
    }
  );
});

//将Router接口导出
module.exports = router;
